<template>
  <el-dialog
    top="5vh"
    width="1000px"
    title="批量导入学生"
    :visible.sync="dialogValue"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="student-import">
      <el-upload
        class="upload-excel"
        action=""
        :auto-upload="false"
        :show-file-list="false"
        accept=".xlsx,.xls"
        :on-change="handleFileChange"
      >
        <el-button type="primary">选择Excel文件</el-button>
        <div class="el-upload__tip" slot="tip">只能上传 xlsx/xls 格式文件</div>
      </el-upload>

      <div v-if="previewData.length > 0" class="preview-table">
        <h3>数据预览</h3>
        <el-table :data="previewData" border style="width: 100%" max-height="500px">
          <el-table-column prop="student_no" label="学号" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="gender" label="性别" width="80" />
          <el-table-column prop="grade" label="年级" width="120" />
          <el-table-column prop="class_name" label="班级" />
        </el-table>

        <div class="action-buttons">
          <el-button type="success" @click="handleImport" :loading="importing">
            确认导入
          </el-button>
          <el-button @click="resetImport">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import * as XLSX from 'xlsx'
import {http} from "../../api";

export default {
  name: 'StudentImport',

  data() {
    return {
      dialogValue: false,
      previewData: [],
      importing: false
    }
  },

  methods: {
    handleFileChange(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const data = e.target.result
        const workbook = XLSX.read(data, {type: 'array'})
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]

        // Convert Excel data to JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1})

        // Skip header row and transform data
        const transformedData = jsonData.slice(1).map(row => ({
          student_no: row[0],
          name: row[1],
          gender: row[2],
          grade: row[3],
          class_name: row[4]
        }))

        // 检查数据是否存在重复（相同年级下的班级和学号不能同时相同）
        const duplicates = []
        const studentMap = new Map()

        transformedData.forEach((student, index) => {
          const key = `${student.grade}-${student.class_name}-${student.student_no}`
          if (studentMap.has(key)) {
            duplicates.push({
              index: index + 2, // Excel行号从2开始（1是表头）
              grade: student.grade,
              student_no: student.student_no,
              class_name: student.class_name
            })
          } else {
            studentMap.set(key, true)
          }
        })

        if (duplicates.length > 0) {
          const errorMsg = duplicates.map(d =>
            `第${d.index}行：${d.grade}年级「${d.class_name}」班的学号「${d.student_no}」重复`
          ).join('\n')
          this.$message.error('发现重复数据：\n' + errorMsg)
          this.previewData = []
          return
        }

        this.previewData = transformedData
      }
      reader.readAsArrayBuffer(file.raw)
    },

    async handleImport() {
      if (this.previewData.length === 0) {
        this.$message.warning('没有可导入的数据')
        return
      }

      try {
        this.importing = true
        // TODO: 调用后端API进行导入
        const response = await http.student.batchCreate(this.previewData)
        this.$message.success('导入成功')
        this.resetImport()
        this.$emit('import-success')
      } catch (error) {
        this.$message.error('导入失败：' + error.message)
      } finally {
        this.importing = false
      }
    },

    resetImport() {
      this.previewData = []
      this.dialogValue = false
    },

    open() {
      this.dialogValue = true
    }
  }
}
</script>

<style lang="scss" scoped>
.student-import {
  padding: 20px;
}

.preview-table {
  margin-top: 20px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.upload-excel {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px;
  background: #fafafa;
}

.el-upload__tip {
  margin-top: 10px;
  color: #606266;
}
</style>
